/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import Vue from 'vue'
import VueRouter from 'vue-router'
import { filterCreateRouterList } from '@/utils/permission'

import Layout from '@/layout/index.vue'

Vue.use(VueRouter as any)

export const constantRoutes: Array<any> = [
  {
    path: '/redirect',
    component: () => import('@/views/redirect.vue'),
    hidden: true,
  },

  {
    path: '/404',
    component: () => import('@/views/404.vue'),
    hidden: true,
  },

  {
    path: '/',
    redirect: '/layout/home',
  },

  {
    // 考勤设置
    path: '/layout',
    component: Layout,
    redirect: '/layout/home',
    name: 'layout',
    meta: { title: '工作台', icon: 'line-setting', hideBreadcrumb: true },
    permissionKey: 'home',
    children: [
      {
        // 排班考勤
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: { title: '首页', icon: 'gift', hideBreadcrumb: true },
        realPath: '/layout/home',
        permissionKey: 'home',
        children: [],
      },
    ],
  },

  { path: '*', redirect: '/404', hidden: true },
]

const createRouter = (routes: any = null) => {
  return new (VueRouter as any)({
    // scrollBehavior功能只在 HTML5 history 模式下可用，当切换到新路由时，想要页面滚到顶部，或者是保持原先的滚动位置，就像重新加载页面那样
    // mode: 'history',
    // scrollBehavior: (to: any, from: any, savedPosition: any) => {
    //   if (savedPosition) {
    //     // 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用
    //     return savedPosition
    //   } else {
    //     return { x: 0, y: 0 }
    //   }
    // },
    base: process.env.BASE_URL,
    routes: routes || filterCreateRouterList(),
  })
}

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter(routes: any): void {
  const newRouter = createRouter(routes)
  router.matcher = newRouter.matcher // reset router
  router.options = newRouter.options // reset router
}

// 重定向首页
export function redirectHome(): void {
  location.href = '/'
}

// 添加路由
export function addRouters(routers: any): void {
  router.addRoutes(routers)
}

export default router
